<script setup>
import reserveApi from "@/api/reserve.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import router from "@/router/index.js";
import WangEditor from "@/components/WangEditor.vue";

import { useTokenStore } from '@/store/token.js'
const userInfoStore = useUserInfoStore()


console.log('单独存放的 userId:', userInfoStore.userId)



//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const reserveQuery = ref({
  name: '',
  phone: '',
  courseId:'',
  userId: userInfoStore.userId,
  page: 1,
  limit: 10
})

/*reserveApi.list(reserveQuery.value).then(result => {
    list.value = result.data.records
    total.value = result.data.total
})*/

const loadData = () => {
  reserveApi.list(reserveQuery.value).then(result => {
    if (result.code == 0) {
      list.value = result.data.records
      total.value = result.data.total
    }
  })
}

loadData()

const onSearch = () => {
  reserveQuery.value.page = 1
  loadData()
}

const reset = () => {
  reserveQuery.value.courseId = ''
  reserveQuery.value.userId = userInfoStore.userId


}

//根据id删除
const deleteById = async (row) => {
  if (!row || !row.id) {
    ElMessage.error('未获取到预约记录ID');
    return;
  }

  try {
    await ElMessageBox.confirm('您确认要取消预约吗?', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    // 删除预约记录
    const delRes = await reserveApi.deleteById(row.id);
    if (delRes.code !== 0) {
      ElMessage.error(delRes.msg || '删除预约失败');
      return;
    }

    // 如果有 courseId，则把课程状态改回可预约 (status = 1)
    if (row.courseId) {
      const courseRes = await courseApi.update({ id: row.courseId, status: 1 });
      if (courseRes.code === 0) {
        ElMessage.success('取消成功');
      } else {
        ElMessage.warning('取消成功，但课程状态未更新: ' + (courseRes.msg || '未知错误'));
      }
    } else {
      ElMessage.success('取消成功');
    }

    // 刷新列表
    loadData();
  } catch (err) {
    // 用户点取消会抛出 'cancel' / 'close'，忽略；其余的打印并提示
    if (err !== 'cancel' && err !== 'close') {
      console.error(err);
      ElMessage.error('操作失败，请稍后重试');
    }
  }
}


//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
  console.log('多选', rows)
  ids.value = rows.map(function (row) {
    return row.id;
  })
  console.log(ids.value)
}

const deleteAll = () => {
  ElMessageBox.confirm(
      '您确认要删除么?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    reserveApi.deleteAll(ids.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  })
}

//添加、修改
const dialogFormVisible = ref(false)
const reserve = ref({})
const showAddDialog = () => {
  reserve.value = {
    userId: userInfoStore.userId   // ←直接带进去

  }
  dialogFormVisible.value = true
}

const showUpdateDialog = (id) => {
  dialogFormVisible.value = true
  reserve.value = {}
  reserveApi.selectById(id).then(result => {
    if (result.code == 0) {
      reserve.value = result.data
    }
  })
}

const addOrUpdate = () => {
  if (reserve.value.id) {
    reserveApi.update(reserve.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  } else {
    reserveApi.add(reserve.value).then(result => {
      if (result.code == 0) {
        ElMessage.success(result.msg)
        dialogFormVisible.value = false
        loadData()
      } else {
        ElMessage.error(result.msg)
      }
    })
  }
}




// 修改对话框
const updateDialogVisible = ref(false)

const showUpdateDialogg = (id) => {
  updateDialogVisible.value = true
  reserve.value = {}
  reserveApi.selectById(id).then(result => {
    if (result.code == 0) {
      const data = result.data
      // 找到课程名称
      const course = courseList.value.find(c => c.id === data.courseId)
      data.courseName = course ? course.name : ''
      reserve.value = data
    }
  })
}


// 单独的更新方法（只更新分数和评价）
const updateReserve = () => {
  const payload = {
    id: reserve.value.id,
    score: reserve.value.score,
    comment: reserve.value.comment
  }
  reserveApi.update(payload).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg)
      updateDialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(result.msg)
    }
  })
}



//el-switch状态切换
const handleSwitchChange = (row) => {
  console.log(row)
  const reserve = {}
  reserve.id = row.id
  reserve.status = row.status
  reserveApi.update(reserve).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  })
  /*reserveApi.updateStatus(row.id, row.status).then(result => {
      if (result.code == 0) {
          ElMessage.success(result.msg)
      } else {
          ElMessage.error(result.msg)
      }
  })*/
}

//图片上传
const handleAvatarSuccess = (result) => {
  reserve.value.avatar = result.data
}

import courseApi from "@/api/course.js";
import userApi from "@/api/user.js";
import tokenStore from "@/api/user.js";
import {useUserInfoStore} from "@/store/userInfo.js";
const headers = ref({
  //携带token传递到后端
  Authorization: tokenStore.token
});

//查找所有的课程
const courseList = ref([])
courseApi.selectAll().then(result => {
  if (result.code == 0) {
    courseList.value = result.data
  }
})

//查找所有的user
const userList = ref([])
userApi.selectAll().then(result => {
  if (result.code == 0) {
    userList.value = result.data
  }
})


//下拉事件
const selectChange = (value) => {
  console.log(value)
}


//富文本编辑器
const onEditorChange = (introduction) => {
  reserve.value.introduction = introduction
}

const dialogIntroductionVisible = ref(false)
const introduction = ref('')
const showIntroduction = (intro) => {
  dialogIntroductionVisible.value = true
  introduction.value = intro
}
</script>

<template>
  <el-card class="">
    <template #header>
      <div class="header">
<!--
        <el-button type="success" @click="showAddDialog">添加预约</el-button>
-->
      </div>
    </template>
    <el-form :inline="true">
      <el-form-item label="课程">
        <el-select @change="selectChange" v-model="reserveQuery.courseId" clearable placeholder="请选择课程"
                   style="width: 150px">
          <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" :label-width="100">
        <el-date-picker
            v-model="reserveQuery.beginUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
        />
        <el-date-picker
            v-model="reserveQuery.endUpdateTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="ID"/>
      <el-table-column prop="courseId" label="课程ID"/>
      <el-table-column prop="courseName" label="课程"/>
      <el-table-column prop="score" label="分数">
      </el-table-column>

      <el-table-column prop="comment" label="评价">

      </el-table-column>
      <!-- <el-table-column prop="avatar" label="头像"/> -->
      <el-table-column prop="updateTime" label="预约时间" width="180px"/>
      <el-table-column align="center" width="200px" fixed="right" label="操作">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="showUpdateDialogg(row.id)">修改</el-button>
          <el-button size="small" type="danger" @click="deleteById(row)">取消</el-button>
          <!--
                    <el-button size="small" type="warning" @click="showIntroduction(row.introduction)">备注</el-button>
          -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="reserveQuery.page"
        v-model:page-size="reserveQuery.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @change="loadData"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <!--添加弹出框-->
<!--  <el-dialog v-model="dialogFormVisible" :title="title" width="60%" :lock-scroll="false">
    <el-form :model="reserve">
      <el-form-item label="课程">
        <el-select @change="selectChange" v-model="reserve.courseId" clearable placeholder="请选择课程"
                   style="width: 150px">
          <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.name"
              :value="course.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>-->



  <!-- 修改弹出框 -->
  <el-dialog v-model="updateDialogVisible" title="修改内容" width="50%" :lock-scroll="false">
    <el-form :model="reserve" label-width="100px">
      <!-- 课程名称，只读 -->
      <el-form-item label="课程">
        <el-input v-model="reserve.courseName" disabled />
      </el-form-item>

      <!-- 分数，可编辑 -->
      <el-form-item label="分数">
        <el-input-number v-model="reserve.score" :min="0" :max="100" />
      </el-form-item>

      <!-- 评价，可编辑 -->
      <el-form-item label="评价">
        <el-input v-model="reserve.comment" type="textarea" rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateReserve">保存</el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="dialogIntroductionVisible" :title="title" width="60%" :lock-scroll="false">
    <div v-html="introduction"></div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogIntroductionVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>